"use strict";

const Skyone = {
    Home: location.href,
    Pages: 4,
    xhr: null,
    xhrUrl: '',
    load: function (url, success, err) {
        // 如果连接为本页链接，返回假
        if (url === this.xhrUrl) return false;
        this.xhrUrl = url;
        if (this.xhr) {
            // 当前请求存在，则终止请求
            this.xhr.abort();
        }
        this.xhr = $.ajax({
            type: "GET",
            url: url,
            timeout: 10000,
            success: (date) => {
                success(date);
                this.xhrUrl = "";
                MathJax && MathJax.typeset();
            },
            error: (xhr, error) => {
                if (error === "abort") {
                    err && err();
                } else {
                    window.location.href = url;
                }
                this.xhrUrl = "";
            }
        });
    },
    loading: function () {
        const w = window.innerWidth;
        const css = '<style class="loaderstyle" id="loaderstyle' + w + '">' +
            '@-moz-keyframes loader' + w + '{100%{background-position:' + w + 'px 0}}' +
            '@-webkit-keyframes loader' + w + '{100%{background-position:' + w + 'px 0}}' +
            '.loader' + w + '{-webkit-animation:loader' + w + ' 3s linear infinite;-moz-animation:loader' + w + ' 3s linear infinite;}' +
            '</style>';
        $('.loaderstyle').remove()
        $('head').append(css)
        $('#loader').removeClass().addClass('loader' + w).show()
    },
    loaded: function () {
        $('#loader').removeClass().hide()
    },
    isPhone: function () {
        return "ontouchstart" in window;
    },
    pushState: function () {
        if (!(window.history && history.pushState)) return;

        history.replaceState(
            {
                url: this.Home,
                title: document.title
            },
            document.title,
            this.Home
        );
        window.addEventListener(
            "popstate",
            (e,) => {
                const state = e.state;
                if (!state) return;
                if (state.url === this.Home) {
                    // 返回主页
                    const preview = $("#preview"),
                        container = $("#container");
                    preview.css("position", "fixed");
                    setTimeout(() => {
                        preview.removeClass("show");
                        container.show();
                        window.scrollTo(0, parseInt($("#container").data("scroll")));
                        setTimeout(() => {
                            preview.html('');
                            $(window).trigger("resize");
                        }, 300);
                    }, 0);
                } else {
                    this.loading();
                    this.load(state.url, (date) => {
                        document.title = state.t;
                        $("#preview").html($(date).filter("#single"));
                        this.preview();
                        setTimeout(this.player, 0);
                    });
                }
            }
        );
    },
    HS: function (tag, flag) {
        const id = tag.data("id") || 0,
            url = tag.attr("href"),
            title = tag.attr("title") + " - " + $("#config-title").text();

        if (!$("#preview").length || !(window.history && history.pushState)) {
            location.href = url;
        } else {
            this.loading();
            const state = {id, title, url};
            this.load(url, (data) => {
                if (!$(data).filter("#single").length) {
                    location.href = url;
                    return;
                }
                switch (flag) {
                    case "push":
                        history.pushState(state, title, url);
                        break;
                    case "replace":
                        history.replaceState(state, title, url);
                        break;
                }
                document.title = title;
                $("#preview").html($(data).filter("#single"))
                switch (flag) {
                    case 'push':
                        this.preview()
                        break;
                    case 'replace':
                        window.scrollTo(0, 0)
                        this.loaded()
                        break;
                }
                setTimeout(() => {
                    this.player();
                    $("#top").show();
                    const comment = $("#gitalk-container");
                    if (comment.data("ae") === true) {
                        comment.click();
                    }
                }, 0);
            })
        }
    },
    preview: function () {
        $("#preview").one(
            "transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd",
            () => {
                if (!!$("preview").hasClass("show")) {
                    $("#container").hide();
                } else {
                    $("#container").show();
                }
                this.loaded();
            }
        );
        setTimeout(function () {
            $('#preview').addClass('show');
            $('#container').data('scroll', window.scrollY);
            setTimeout(function () {
                $('#preview').css({
                    'position': 'fixed',
                    'overflow-y': 'auto'
                });
            }, 500);
        }, 0);
    },
    player: function () {
        const audio = $("audio");
        if (!audio.length) {
            $(".icon-play").css({
                'color': "#dedede",
                "cursor": "not-allow"
            });
            return;
        }
        const sourceSrc = $("#audio source").eq(0).attr("src");
        if ((!sourceSrc) && (!audio[0].src)) {
            const list = $("#audio-list li"),
                mp3 = list.eq([Math.floor(Math.random() * list.size())]);
            audio[0].src = mp3.data("url");
        }
        if (audio.eq(0).data("autoplay") === true) {
            audio[0].play();
        }

        audio.on({
            'timeupdate': function () {
                const progress = audio[0].currentTime / audio[0].duration * 100;
                $('.bar').css('width', progress + '%');
                if (progress / 5 <= 1) {
                    audio[0].volume = progress / 5;
                } else {
                    audio[0].volume = 1;
                }
            },
            'ended': function () {
                $('.icon-pause').removeClass('icon-pause').addClass('icon-play')
            },
            'playing': function () {
                $('.icon-play').removeClass('icon-play').addClass('icon-pause')
            }
        })
    },
    F: function (id, w, h) {
        const _height = $(id).parent().height(),
            _width = $(id).parent().width(),
            ratio = h / w;
        if (_height / _width > ratio) {
            id.style.height = _height + 'px';
            id.style.width = _height / ratio + 'px';
        } else {
            id.style.width = _width + 'px';
            id.style.height = _width * ratio + 'px';
        }
        id.style.left = (_width - parseInt(id.style.width)) / 2 + 'px';
        id.style.top = (_height - parseInt(id.style.height)) / 2 + 'px';
    }
}

$(function () {
    const preview = $('#preview'),
        mark = $('#mark'),
        scrollbar = $('.scrollbar');
    if (Skyone.isPhone()) {
        $('body').addClass('touch')
    }
    if (preview.length) {
        const cover = {};
        cover.tag = $('#cover');
        cover.width = cover.tag.attr('width');
        cover.height = cover.tag.attr('height');
        ;(cover.over = function () {
            mark.height(window.innerHeight)
        })();
        if (cover.tag.prop('complete')) {
            setTimeout(function () {
                cover.tag.load()
            }, 0)
        }
        cover.tag.on('load', function () {
            ;(cover.fill = function () {
                let _w = mark.width(), _h = mark.height(), x, y, i, e;
                e = (_w >= 1000 || _h >= 1000) ? 1000 : 500;
                if (_w >= _h) {
                    i = _w / e * 50;
                    y = i;
                    x = i * _w / _h;
                } else {
                    i = _h / e * 50;
                    x = i;
                    y = i * _h / _w;
                }
                $('.layer').css({
                    'width': _w + x,
                    'height': _h + y,
                    'marginLeft': -0.5 * x,
                    'marginTop': -0.5 * y
                })
                if (!cover.width) {
                    cover.width = cover.tag.width();
                    cover.height = cover.tag.height();
                }
                Skyone.F($('#cover')[0], cover.width, cover.height)
            })();
            setTimeout(function () {
                $('html, body').removeClass('loading')
            }, 1000)
            $('#mark').parallax()
            const vibrant = new Vibrant(cover.tag[0]);
            const swatches = vibrant.swatches();
            if (swatches['DarkVibrant']) {
                $('#vibrant polygon').css('fill', swatches['DarkVibrant'].getHex())
                $('#vibrant div').css('background-color', swatches['DarkVibrant'].getHex())
            }
            if (swatches['Vibrant']) {
                $('.icon-menu').css('color', swatches['Vibrant'].getHex())
                $('.icon-search').css('color', swatches['Vibrant'].getHex())
            }
        })
        if (!cover.tag.attr('src')) {
            alert('Please set the post thumbnail')
        }
        $('#preview').css('min-height', window.innerHeight)
        Skyone.pushState()
        $('.pview a').addClass('pviewa')
        let T;
        $(window).on('resize', function () {
            clearTimeout(T)
            T = setTimeout(function () {
                if (!Skyone.isPhone() && location.href === Skyone.Home) {
                    cover.over()
                    cover.fill()
                }
                if ($('#loader').attr('class')) {
                    Skyone.loading()
                }
            }, 500)
        })
    } else {
        $('#single').css('min-height', window.innerHeight)
        setTimeout(function () {
            $('html, body').removeClass('loading')
        }, 1000)
        window.addEventListener('popstate', function (e) {
            if (e.state) location.href = e.state.u;
        })
        Skyone.player();
        $('.icon-icon, .image-icon').attr('href', '/')
        $('#top').show()
    }
    $(window).on('scroll', function () {
        if (scrollbar.length && !Skyone.isPhone() && !$('.icon-images').hasClass('active')) {
            const wt = $(window).scrollTop(),
                tw = $('#top').width(),
                dh = document.body.scrollHeight,
                wh = $(window).height();
            const width = tw / (dh - wh) * wt;
            $('.scrollbar').width(width)
            if (wt > 80 && window.innerWidth > 800) {
                $('.subtitle').fadeIn()
            } else {
                $('.subtitle').fadeOut()
            }
        }
    })
    $(window).on('touchmove', function (e) {
        if ($('body').hasClass('mu')) {
            e.preventDefault()
        }
    })

    // 搜索
    const searchFunc = function (path, search_id, content_id) {
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                const datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                //ID选择器
                const $input = document.getElementById(search_id);
                const $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    let str = '<ul class=\"search-result-list\">';
                    const keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // 本地搜索主要部分
                    datas.forEach(function (data) {
                        let isMatch = true;
                        const data_title = data.title.trim().toLowerCase();
                        const data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        const data_url = data.url;
                        let index_title = -1;
                        let index_content = -1;
                        let first_occur = -1;
                        // 只匹配非空文章
                        if (data_title && data_content) {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // 返回搜索结果
                        if (isMatch) {
                            //结果标签
                            str += "<li><a href='" + data_url + "' class='search-result-title' target='_blank'>" + data_title + "</a>";
                            const content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // 拿出含有搜索字的部分
                                let start = first_occur - 6;
                                let end = first_occur + 6;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 10;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                let match_content = content.substr(start, end);
                                // 列出搜索关键字，定义class加高亮
                                keywords.forEach(function (keyword) {
                                    const regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                })
                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                        }
                    })
                    $resultContent.innerHTML = str;
                })
            }
        })
    };
    const path = "/search.xml";
    if (document.getElementById('local-search-input') !== null) {
        searchFunc(path, 'local-search-input', 'local-search-result');
    }

    let typed = null;
    $('body').on('click', function (e) {
        let t;
        let tag = $(e.target).attr('class') || '',
            rel = $(e.target).attr('rel') || '';
        // .content > ... > img
        if (e.target.nodeName === "IMG" && $(e.target).parents('div.content').length > 0) {
            tag = 'pimg';
        }
        if (!tag && !rel) return;
        switch (true) {
            // nav menu
            case (tag.indexOf('switchmenu') !== -1):
                window.scrollTo(0, 0)

                $('html, body').toggleClass('mu');
                if (typed !== null) {
                    typed.destroy();
                    typed = null;
                } else {
                    if ($("#hitokoto").data('st') === true) {
                        $.get("https://v1.hitokoto.cn/", function (data) {
                            const str = data.hitokoto + " ——  By ";
                            const options = {
                                strings: [str + data.from,],
                                typeSpeed: 90,
                                startDelay: 500,
                                //backDelay: 500,
                                //backSpeed: 50,//回退速度
                                //loop: true,
                            };
                            typed = new Typed(".hitokoto .typed", options);
                        })
                    }
                }
                return false;
            //search
            case (tag.indexOf('switchsearch') !== -1):
                $('body').removeClass('mu')
                if (typed !== null) {
                    typed.destroy();
                    typed = null;
                }
                setTimeout(function () {
                    Skyone.HS($(e.target), 'push')
                    $('.toc').fadeIn(1000);
                    searchFunc(path, 'local-search-input', 'local-search-result');
                }, 300)
                return false;
            // next page
            case (tag.indexOf('more') !== -1):
                tag = $('.more');
                if (tag.data('status') === 'loading') {
                    return false
                }
                const num = parseInt(tag.data('page')) || 1;
                if (num === 1) {
                    tag.data('page', 1)
                }
                if (num >= Skyone.Pages) {
                    return
                }
                tag.html('加载中...').data('status', 'loading')
                Skyone.loading()
                Skyone.load(tag.attr('href'), function (data) {
                    const link = $(data).find('.more').attr('href');
                    if (link) {
                        tag.attr('href', link).html('加载更多').data('status', 'loaded')
                        tag.data('page', parseInt(tag.data('page')) + 1)
                    } else {
                        $('#pager').remove()
                    }
                    const tempScrollTop = $(window).scrollTop();
                    $('#primary').append($(data).find('.post'))
                    $(window).scrollTop(tempScrollTop + 100);
                    Skyone.loaded()
                    $('html,body').animate({scrollTop: tempScrollTop + 400}, 500);
                }, function () {
                    tag.html('加载更多').data('status', 'loaded')
                })
                return false;
            // home
            case (tag.indexOf('icon-home') !== -1):
                $('.toc').fadeOut(100);
                if ($('#preview').hasClass('show')) {
                    history.back();
                } else {
                    location.href = $('.icon-home').data('url')
                }
                return false;
            // qrcode
            case (tag.indexOf('icon-scan') !== -1):
                const iconScan = $('.icon-scan')
                if (iconScan.hasClass('tg')) {
                    $('#qr').toggle()
                } else {
                    iconScan.addClass('tg')
                    $('#qr').qrcode({width: 128, height: 128, text: location.href}).toggle()
                }
                return false;
            // audio play
            case (tag.indexOf('icon-play') !== -1):
                $('#audio')[0].play()
                $('.icon-play').removeClass('icon-play').addClass('icon-pause')
                return false;
            // audio pause
            case (tag.indexOf('icon-pause') !== -1):
                $('#audio')[0].pause()
                $('.icon-pause').removeClass('icon-pause').addClass('icon-play')
                return false;
            // history state
            case (tag.indexOf('cover') !== -1):
                Skyone.HS($(e.target).parent(), 'push')
                return false;
            // history state
            case (tag.indexOf('posttitle') !== -1):
                Skyone.HS($(e.target), 'push')
                return false;
            // prev, next post
            case (rel === 'prev' || rel === 'next'):
                if (rel === 'prev') {
                    t = $('#prev_next a')[0].text;
                } else {
                    t = $('#prev_next a')[1].text;
                }
                $(e.target).attr('title', t)
                Skyone.HS($(e.target), 'replace')
                return false;
            // toc
            case (tag.indexOf('toc-text') !== -1 || tag.indexOf('toc-link') !== -1
                || tag.indexOf('toc-number') !== -1):
                let hash = '';
                if (e.target.nodeName === 'SPAN') {
                    hash = $(e.target).parent().attr('href')
                } else {
                    hash = $(e.target).attr('href')
                }
                const to = $("a.headerlink[href='" + hash + "']")
                $("html,body").animate({
                    scrollTop: to.offset().top - 50
                }, 300);
                return false;
            // quick view
            case (tag.indexOf('pviewa') !== -1):
                $('body').removeClass('mu')
                if (typed !== null) {
                    typed.destroy();
                    typed = null;
                }
                setTimeout(function () {
                    Skyone.HS($(e.target), 'push')
                    $('.toc').fadeIn(1000);
                }, 300)
                return false;
            // photoswipe
            case (tag.indexOf('pimg') !== -1):
                const pswpElement = $('.pswp').get(0);
                if (pswpElement) {
                    const items = [];
                    let index = 0;
                    const imgs = [];
                    $('.content img').each(function (i, v) {
                        // get index
                        if (e.target.src === v.src) {
                            index = i;
                        }
                        const item = {
                            src: v.src,
                            w: v.naturalWidth,
                            h: v.naturalHeight
                        };
                        imgs.push(v);
                        items.push(item);
                    });
                    const options = {
                        index: index,
                        shareEl: false,
                        zoomEl: false,
                        allowRotationOnUserZoom: true,
                        history: false,
                        getThumbBoundsFn: function (index) {
                            // See Options -> getThumbBoundsFn section of documentation for more info
                            const thumbnail = imgs[index],
                                pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                                rect = thumbnail.getBoundingClientRect();

                            return {x: rect.left, y: rect.top + pageYScroll, w: rect.width};
                        }
                    };
                    const lightBox = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
                    lightBox.init();
                }
                return false;
            // comment
            case tag.indexOf("comment") !== -1:
                const comment = $('#gitalk-container');
                if (comment.data('enable') === true) {
                    Skyone.loading();
                    const comment = $('#gitalk-container');
                    const gitalk = new Gitalk({
                        clientID: comment.data('ci'),
                        clientSecret: comment.data('cs'),
                        repo: comment.data('r'),
                        owner: comment.data('o'),
                        admin: comment.data('a'),
                        id: md5(window.location.pathname),
                        distractionFreeMode: comment.data('d')
                    })
                    $(".comment").removeClass("link")
                    gitalk.render('gitalk-container')
                    Skyone.loaded();
                } else {
                    $('#gitalk-container').html("评论已关闭");
                }
                return false;
            default:
                return true;
        }
    })
    // 是否自动展开评论
    const comment = $("#gitalk-container");
    if (comment.data('ae') === true) {
        comment.click();
    }
})

